package com.taotao.cart.controller;

import com.taotao.cart.service.CartService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.common.util.JsonUtils;
import com.taotao.manager.pojo.TbItem;
import com.taotao.manager.pojo.TbUser;
import com.taotao.manager.service.ItemService;
import com.taotao.sso.service.UserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private ItemService itemService;

    @Value("${TT_TOKEN_KEY}")
    private String TT_TOKEN_KEY;
    @Value("${TT_CART_KEY}")
    private String TT_CART_KEY;

    /**
     * url:/cart/add/{itemId}?num=2 参数:商品id,num,返回值:jsp页面
     *
     * @param request
     * @param response
     * @param itemId
     * @param num
     * @return
     */
    @RequestMapping("/cart/add/{itemId}")
    public String addItemCart(HttpServletRequest request, HttpServletResponse response, @PathVariable Long itemId, @RequestParam(defaultValue = "1") Integer num) {
        String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
        TaotaoResult result = userLoginService.getUserByToken(token);
        TbItem tbItem = itemService.getItemById(itemId);
        if (result.getStatus() == 200) {
            //如果用户已登录,调用service方法
            TbUser user = (TbUser) result.getData();
            cartService.addItemCart(user.getId(), tbItem, num);
        } else {
            //如果没有登录,调用设置到cookie的方法
            //先根据cookie获取购物车列表
            List<TbItem> cartList = getCookieCartList(request);
            boolean flag = false;//用来标志cookieList中是否含有该商品,没有就为false
            for (TbItem tbItem2 : cartList) {
                if (tbItem2.getId() == itemId.longValue()) {
                    //找到列表中的商品更新数量
                    tbItem2.setNum(tbItem2.getNum() + num);
                    flag = true;
                    break;
                }
            }
            //如果flag为true证明购物车中已经存在该商品,更新数量后,再设置回cookie即可
            //flag为false,则需要添加商品到购物车,然后再设置回cookie
            if (!flag) {
                tbItem.setNum(num);
                if (tbItem.getImage() != null) {
                    tbItem.setImage(tbItem.getImage().split(",")[0]);
                }
                cartList.add(tbItem);
            }
            CookieUtils.setCookie(request, response, TT_CART_KEY, JsonUtils.objectToJson(cartList), 7 * 24 * 3600, true);
        }
        return "cartSuccess";
    }
    @RequestMapping("/cart/cart")
    public String getCartList(HttpServletRequest request) {
        String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
        TaotaoResult result = userLoginService.getUserByToken(token);
        if (result.getStatus() == 200) {
            //如果用户已登录,调用service方法
            TbUser user = (TbUser) result.getData();
            List<TbItem> cartList = cartService.getCartList(user.getId());
            request.setAttribute("cartList",cartList);
        } else {
            List<TbItem> cartList = getCookieCartList(request);
            request.setAttribute("cartList",cartList);
        }
        return "cart";
    }
    @RequestMapping("/cart/update/num/{itemId}/{num}")
    @ResponseBody
    public TaotaoResult updateCartByItemId(HttpServletRequest request,HttpServletResponse response,@PathVariable Long itemId,@PathVariable Integer num) {
        String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
        TaotaoResult result = userLoginService.getUserByToken(token);
        if (result.getStatus() == 200) {
            TbUser user = (TbUser) result.getData();
            cartService.updateItemCartByItemId(user.getId(), itemId, num);
        } else {
            updateCookieCart(request, response, itemId, num);
        }
        return  TaotaoResult.ok();
    }

    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCartItemByItemId(HttpServletRequest request, HttpServletResponse response, @PathVariable Long itemId) {
        String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
        TaotaoResult result = userLoginService.getUserByToken(token);
        if (result.getStatus() == 200) {
            TbUser user = (TbUser) result.getData();
            cartService.deleteItemCartByItemId(user.getId(), itemId);
        } else {
            deleteCookieCartByItemId(request, response, itemId);
        }
        return "redirect:/cart/cart.html";
    }
    /**
     * 从cookie中获取购物车列表
     * @param request
     * @return
     */
    private List<TbItem> getCookieCartList(HttpServletRequest request) {
        String jsonStr = CookieUtils.getCookieValue(request, TT_CART_KEY, true);
        if (StringUtils.isNotBlank(jsonStr)) {
            List<TbItem> list = JsonUtils.jsonToList(jsonStr, TbItem.class);
            return list;
        }
        return new ArrayList<>();
    }

    /**
     * 更新cookie中的购物车信息
     * @param request
     * @param response
     * @param itemId
     * @param num
     */
    private void updateCookieCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) {
        List<TbItem> cartList = getCookieCartList(request);
        boolean flag=false;
        for (TbItem tbItem2 : cartList) {
            if (tbItem2.getId() == itemId.longValue()) {
                //找到列表中的商品更新数量
                tbItem2.setNum(tbItem2.getNum() + num);
                flag = true;
                break;
            }
        }
        if (flag) {
            CookieUtils.setCookie(request, response, TT_CART_KEY, JsonUtils.objectToJson(cartList), 7 * 24 * 3600, true);
        }
    }

    private void deleteCookieCartByItemId(HttpServletRequest request, HttpServletResponse response, Long itemId) {
        List<TbItem> cartList = getCookieCartList(request);
        boolean flag=false;
        for (TbItem tbItem2 : cartList) {
            if (tbItem2.getId() == itemId.longValue()) {
                cartList.remove(tbItem2);
                flag = true;
                break;
            }
        }
        if (flag) {
            CookieUtils.setCookie(request, response, TT_CART_KEY, JsonUtils.objectToJson(cartList), 7 * 24 * 3600, true);
        }
    }

}
